package com.ansatsing.chat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class ChatClient {
    private final String host;
    private final int port;

    public ChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }
    public void run(){
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChatClientHandlerInitializer());
            try {
                Channel channel = bootstrap.connect(host,port).sync().channel();
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                while(true){
                    try {
                        channel.write(reader.readLine()+"\r\n");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }/* catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }*/
        }finally {
            group.shutdownGracefully();
        }
    }
    public static void main(String[] args) {
        new ChatClient("39.108.166.35",8888).run();
    }
}
